<?php
namespace Admin\Survey\Controllers;

use Helpers\Main;
use Helpers\Tool;
use Helpers\Assets;
use Admin\Models\ask\XhaskQuestion;
use Admin\Models\ask\XhaskOption;
use Admin\Models\ask\XhaskAnswer;
use Admin\Models\ask\XhaskSurvey;
use Admin\Models\ask\XhaskSurveyinfo;
use Admin\Models\user\XhsysUser;
use Helpers\User;

class IndexController extends ControllerBase
{

    /**
     * 问卷首页
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by ck 20171214
     * modify by ck 20180408    添加公司问卷
     */
    public function indexAction()
    {
        $query    = $this->request->getQuery();
        $userId   = $query['userId'] ?: User::getId();
        if (!$userId) {
            return $this->sendViewError('未传入用户禁止访问');
        }
        $this->view->pick('index/index');
        Assets::flatUI();
        try {
            $user = XhsysUser::findFirst($userId);
            if (!$user) {
                throw new \Exception('当前用户不存在');
            }
            $survey = User::isStaff($userId)
                ? XhaskSurvey::getStaffSurvey($userId)
                : XhaskSurvey::getAllowAttendList($userId, $user->iSchoolId, $user->iUserType);
            if (count($survey) <= 0) {
                throw new \Exception('暂无可参加问卷');
            }
            $this->session->set('survey_user', [
                'userId'    => $userId,
                'userName'  => $user->sUserName,
                'surveyId'  => $survey[0]['id']
            ]);
            return $this->response->redirect('survey/index/detail');
            //todo 展示列表页面
//            return $this->view->setVars([
//                'userId'    => $userId,
//                'userName'  => $user->sUserName,
//                'survey'    => $survey
//            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 问卷页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171214
     */
    public function detailAction()
    {
        $info = $this->session->get('survey_user');
        if (!$info['userId']) {
            return $this->sendViewError('未检测到用户信息');
        }
        if (!$info['surveyId']) {
            return $this->sendViewError('未检测到问卷信息');
        }

        try {
            $surveyInfo = XhaskSurveyinfo::findFirst([
                'conditions'    => 'iASId = :surveyId: AND iUserId = :userId:',
                'bind'          => ['surveyId' => $info['surveyId'], 'userId' => $info['userId']]
            ]);
            if ($surveyInfo && $surveyInfo->iEndTime) {
                return $this->sendViewError('您已填写过该问卷');
            }

            $survey = XhaskSurvey::findFirst($info['surveyId']);
            if (!$survey) {
                return $this->sendViewError('找不到问卷信息');
            }
            $queIds = array_filter(explode(',', $survey->mAQId));
            if (!$queIds) {
                return $this->sendViewError('该问卷暂无题目设置');
            }
            if ($survey->bMutable) {
                $survey->bMutable = 0;
                $survey->save();
            }

            $queIds    = implode(',', $queIds);
            $questions = XhaskQuestion::find([
                'columns'       => 'iAQId,sQueTitle,sQueExplain,iQueType,iChooseNum,bRequire',
                'conditions'    => "bDelete = 0 AND iAQId IN ({$queIds})",
            ])->toArray();
            $options = XhaskOption::find([
                'columns'       => 'iAOId,iAQId,sOptionContent',
                'conditions'    => "bDelete = 0 AND iAQId IN ({$queIds})",
            ])->toArray();

            $surveyQueInfo = array();
            foreach($questions as $question) {
                $surveyQueInfo[$question['iAQId']] = $question;
            }
            foreach($options as $option) {
                $surveyQueInfo[$option['iAQId']]['options'][] = $option;
            }

            $this->view->pick('index/detail');
            Assets::flatUI('js/detail.js');
            $this->persistent->set('survey_startTime', time());
            return $this->view->setVars([
                'survey'    => $survey,
                'surveyDom' => self::runSurveyDom(array_values($surveyQueInfo))
            ]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 组合问卷html代码
     *
     * @param $questions
     * @return bool|\simple_html_dom
     *
     * create by ck 20171214
     */
    public static function runSurveyDom($questions)
    {
        include_once(APP_PATH . '/helpers/simple_html_dom.php');
        $surveyDom = str_get_html('<div class="question-list"></div>');
        $index = 1;
        foreach($questions as $question) {
            $questionDom = str_get_html('<div></div>');
            if($question['bRequire']) {
                $questionDom->find('div',0)->must = 'true';
            }
            $must = $question['bRequire'] ? '<span class="must"> *</span>' : '';
            $questionDom->find('div',0)->innertext = "<div class='question-title'>{$index} .{$question['sQueTitle']}{$must}</div>";
            switch($question['iQueType']){
                case 1:         //单选
                    $questionDom->find('div',0)->class = 'question-radio';
                    foreach($question['options'] as $option){
                        $questionDom->find('div',0)->innertext .= '<label class="radio">'
                            . "<input type='radio' value='{$option['iAOId']}' name='{$question['iQueType']}_{$question['iAQId']}' class='custom-radio' />"
                            . '<span class="icons"><span class="icon-unchecked"></span><span class="icon-checked"></span></span>'
                            . $option['sOptionContent']
                            . '</label>';
                    }
                    break;
                case 2:         //多选
                    $questionDom->find('div',0)->class = 'question-checkbox';
                    if($question['iChooseNum']) {
                        $questionDom->find('div',0)->maxChoose = $question['iChooseNum'];
                    }
                    foreach($question['options'] as $option){
                        $questionDom->find('div',0)->innertext .= '<label class="checkbox">'
                            . "<input type='checkbox' value='{$option['iAOId']}' name='{$question['iQueType']}_{$question['iAQId']}[]' class='custom-checkbox' />"
                            . '<span class="icons"><span class="icon-unchecked"></span><span class="icon-checked"></span></span>'
                            . $option['sOptionContent']
                            . '</label>';
                    }
                    break;
                case 4:         //单行文本框
                    $questionDom->find('div',0)->class = 'question-textbox';
                    $questionDom->find('div',0)->innertext .= "<input class='form-control' name='{$question['iQueType']}_{$question['iAQId']}' />";
                    break;
                case 5:         //多行文本框
                    $questionDom->find('div',0)->class = 'question-textarea';
                    $questionDom->find('div',0)->innertext .= "<textarea class='form-control' rows='3' name='{$question['iQueType']}_{$question['iAQId']}'></textarea>";
                    break;
                default: continue;
            }
            $surveyDom->find('div',0)->innertext .= $questionDom;
            unset($questionDom);
            $index++;
        }
        return $surveyDom;
    }

    /**
     * 提交问卷
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171214
     */
    public function submitAction()
    {
        $data = $this->request->getPost();
        $info = $this->session->get('survey_user');
        $this->view->pick('index/submit');

        try {
            $survey = XhaskSurvey::findFirst($info['surveyId']);
            if (!$survey) {
                $this->sendViewError('找不到问卷信息');
            }

            $surveyInfo = XhaskSurveyinfo::findFirst([
                'conditions' => 'iASId = :surveyId: AND iUserId = :userId:',
                'bind' => ['surveyId' => $info['surveyId'], 'userId' => $info['userId']]
            ]);
            if ($surveyInfo) {
                return $this->sendViewError('您已填写过该问卷，无需重复参加，谢谢');
            }

            $this->db->begin();
            foreach ($data as $name => $input) {
                if (!$input) {
                    continue;
                }
                $name = explode('_', $name);
                $answer = [
                    'iUserId' => $info['userId'],
                    'iASId'   => $info['surveyId'],
                    'iAQId'   => $name[1],
                ];
                switch ($name[0]) {
                    case 1: //单选
                        $answer['iAOId'] = $input;
                        break;
                    case 2: //多选，直接保存，跳到下一循环
                        foreach ($input as $option) {
                            $answer['iAOId'] = $option;
                            if (!XhaskAnswer::createRecord($answer)) {
                                throw new \Exception('提交失败：答案保存失败');
                            }
                        }
                        break;
                    case 4: //文本
                    case 5: //多行文本
                        $answer['mAnswer'] = $input;
                        break;
                }
                if ($name[0] == 2) {
                    continue;
                }
                if (!XhaskAnswer::createRecord($answer)) {
                    throw new \Exception('提交失败：答案保存失败');
                }
            }
            $survey->iCompleteNum++; //完成次数+1
            if (!$survey->save()) {
                throw new \Exception('提交失败：问卷更新失败');
            }

            //问卷情况
            $surveyInfo               = new XhaskSurveyinfo();
            $surveyInfo->iUserId      = $info['userId'];
            $surveyInfo->iASId        = $info['surveyId'];
            $surveyInfo->iStartTime   = $this->persistent->get('survey_startTime');
            $surveyInfo->iEndTime     = time();
            $surveyInfo->iTimeCost    = $surveyInfo->iEndTime - $surveyInfo->iStartTime;
            $surveyInfo->sUserIP      = $_SERVER['REMOTE_ADDR'];
            $surveyInfo->sUserOS      = Tool::getOS();
            $surveyInfo->sUserBrowser = Tool::getBrowser();
            if (!$surveyInfo->save()) {
                throw new \Exception('提交失败：问卷信息保存失败');
            }
            $this->db->commit();
            return $this->view->setVar('survey', $survey);
        }
        catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendViewError($e->getMessage());
        }
    }

}

